package com.dmw.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dmw.reggie.dto.SetmealDto;
import com.dmw.reggie.entity.Setmeal;
import com.dmw.reggie.entity.SetmealDish;
import com.dmw.reggie.mapper.SetmealMapper;
import com.dmw.reggie.service.SetmealDishService;
import com.dmw.reggie.service.SetmealService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {

    @Resource
    private SetmealDishService setmealDishService;

    /**
     * 批量删除套餐数据，包括关联表的数据
     * @param ids
     */
    @Override
    public void removeByIds(List<Long> ids) {
        // 删除套餐数据
        super.removeByIds(ids);

        // 删除套餐菜品信息
        LambdaQueryWrapper<SetmealDish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(SetmealDish::getSetmealId, ids);
        setmealDishService.remove(queryWrapper);
    }

    /**
     * 根据 id 查询套餐信息，包括菜品数据
     * @param id
     * @return
     */
    @Override
    public SetmealDto getByIdWithDish(Long id) {
        // 查询套餐数据
        Setmeal setmeal = super.getById(id);
        SetmealDto setmealDto = new SetmealDto();

        // 拷贝
        BeanUtils.copyProperties(setmeal, setmealDto);

        // 查询菜品数据
        LambdaQueryWrapper<SetmealDish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(SetmealDish::getSetmealId, id);
        List<SetmealDish> setmealDishes = setmealDishService.list(queryWrapper);

        setmealDto.setSetmealDishes(setmealDishes);

        return setmealDto;
    }

    @Override
    public void updateWithDish(SetmealDto setmealDto) {
        // 更新套餐表数据
        this.updateById(setmealDto);

        // 删除菜品数据
        LambdaQueryWrapper<SetmealDish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(SetmealDish::getSetmealId, setmealDto.getId());
        setmealDishService.remove(queryWrapper);

        // 新增菜品数据
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        setmealDishes.forEach(i -> {
            i.setSetmealId(setmealDto.getId());
        });
        setmealDishService.saveBatch(setmealDishes);
    }
}
